package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserManager userManager;

    @PostMapping("user/save")
    public Long save(@RequestBody User user) {
        return userManager.save(user);
    }

    @GetMapping("user/findByMobile")
    public User findByMobile(String mobile) {
        return userManager.findByMobile(mobile);
    }

    @PostMapping("/user/login")
    public void sendCode(@RequestBody Map<String, String> map) {
        //1.获取手机号
        String phone = map.get("phone");
        //2.调用manager完成短信发送
        userManager.sendCode(phone);
    }

    @PostMapping("/user/loginVerification")
    public ResponseEntity regAndLogin(@RequestBody Map<String, String> map) {
        return userManager.regAndLogin(map);
    }

    //更新用户信息
    @PostMapping("/user/loginReginfo")
    public ResponseEntity saveUserInfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token) {
        return userManager.saveUserInfo(userInfo, token);
    }

    //更新用户头像
    @PostMapping({"/user/loginReginfo/head", "/users/header"})
    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        return userManager.saveUserInfoHead(headPhoto, token);
    }

    //查询用户信息
    @GetMapping("/users")
    public ResponseEntity findUserInfoById(Long userID, @RequestHeader("Authorization") String token) {
        //1.判断用户id是否为空
        UserInfoVo userInfoVo;

        if (userID != null) {
            userInfoVo = userManager.findUserInfoById(userID);
        } else {
            User user = userManager.findUserFromToken(token);
            userInfoVo = userManager.findUserInfoById(user.getId());
        }

        //2.返回userInfoVo
        return ResponseEntity.ok(userInfoVo);
    }

    //更新用户信息
    @PutMapping("users")
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        return userManager.updateUserInfo(userInfo,token);
    }

}